package advanced.network.demo;


import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

/**
 * 在线聊天室, 客户端:
 * 目标: 实现一个客户可以正常收发信息
 */
public class ChatClient implements Runnable {
    private Socket client;

    public ChatClient(String serverHost, int serverPort, int localPort) {
        try {
            client = new Socket(serverHost, serverPort, InetAddress.getByName("localhost"), localPort);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        try {
            //客户端发消息
            new Thread(new Sender(client)).start();
            new Thread(new Receiver(client)).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

class Sender implements Runnable {
    private BufferedReader console;
    DataOutputStream dos;
    private boolean isRunning = true;
    private Socket client;

    public Sender(Socket client) throws IOException {
        this.client = client;
        console = new BufferedReader(new InputStreamReader(System.in));
        dos = new DataOutputStream(client.getOutputStream());
    }

    @Override
    public void run() {
        while (isRunning) {
            try {
                String msg = console.readLine();
                if (!msg.equals("")) {
                    dos.writeUTF(msg);
                    dos.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
                isRunning=false;
            }
        }
    }

    private void release() {
        Utils.release(dos, client, console);
    }
}

class Receiver implements Runnable {
    private BufferedReader console;
    DataInputStream dis;
    private boolean isRunning = true;
    private Socket client;

    public Receiver(Socket client) throws IOException {
        this.client = client;
        console = new BufferedReader(new InputStreamReader(System.in));
        dis = new DataInputStream(client.getInputStream());
    }

    @Override
    public void run() {
        while (isRunning) {
            try {
                String msg = receive();
                System.out.println(msg);
            } catch (IOException e) {
                isRunning = false;
                release();
            }
        }
    }

    public String receive() throws IOException {
        String dataGram = "";
        dis = new DataInputStream(client.getInputStream());
        dataGram = dis.readUTF();

        return dataGram;
    }

    private void release() {
        Utils.release(dis, client, console);
    }
}